package com.chinawayltd.ews.sample.taskDispatch;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;

import java.util.*;

/**
 * @program: greeProject.timingTaskCenter
 * @description:
 * @author: xiazj
 * @create: 2018-07-14 16:16
 **/
public class TaskCarSelector {

    //匿名Comparator实现
    private static final Comparator<JSONObject> carvldtimeComparator = (JSONObject o1 , JSONObject o2) ->
            o1.getDouble(TaskDispatchConstants.VEHICLE_CARVLDTIME).compareTo(o2.getDouble(TaskDispatchConstants.VEHICLE_CARVLDTIME));

    private static Map<String, Queue<JSONObject>> classifiedOrders(JSONObject vehicle){
        if(vehicle == null || vehicle.isEmpty())throw new RuntimeException("vehicle must be not null and not empty!");

        Map<String, Queue<JSONObject>> result = new HashMap<>();
        for (String key : vehicle.keySet()) {
            JSONObject vehicleObj = vehicle.getJSONObject(key);
            vehicleObj.put(TaskDispatchConstants.VEHICLE_CARNUM, key);

            String volume = vehicleObj.getString(TaskDispatchConstants.VEHICLE_VOLUME);
            if(StringUtils.isBlank(volume)){
                throw new RuntimeException("volume is null or empty in vehicleObj:【" + vehicleObj.toString() + "】");
            }

            Queue<JSONObject> volumeVehicleQueue = result.get(volume);
            if(volumeVehicleQueue == null){
                volumeVehicleQueue = new PriorityQueue<>(carvldtimeComparator);
                result.put(volume, volumeVehicleQueue);
            }
            volumeVehicleQueue.offer(vehicleObj);

        }
        return result;
    }

    public static TaskCarSelector initialize(JSONObject vehicle, JSONObject location){
        return new TaskCarSelector(classifiedOrders(vehicle), location);
    }

    private TaskCarSelector() {}

    private TaskCarSelector(Map<String, Queue<JSONObject>> volumeVehicleMap, JSONObject location) {
        this.volumeVehicleMap = volumeVehicleMap;
        this.location = location;
    }

    /**
     * 不同类型的车辆集合
     **/
    private Map<String, Queue<JSONObject>> volumeVehicleMap;

    /**
     * 站点信息
     **/
    private JSONObject location;

    /**
     * 根据订单选择合适的车辆
     * @param order
     * @return
     */
    public JSONObject choiceTransportVehicle(JSONObject order){
        //获取订单装货站点
        String pickup = order.getString(TaskDispatchConstants.TASKLIST_PICKUP);
        //根据装货站点找出站点可用车型
        JSONObject locationInfo = this.location.getJSONObject(pickup);
        JSONArray carType = locationInfo.getJSONArray(TaskDispatchConstants.LOCATION_CARTYPE);

        if(carType.size() > 0){
            Queue<JSONObject> volumeVehicleQueue = volumeVehicleMap.get(carType.getString(0));
            return volumeVehicleQueue.poll();
        }

        return null;
    }
}
